/* CalSyncUm 
 * Copyright (c) 2006,2007 Arthur van Bunningen
 * Based on L-dopa Calendar Sync, Copyright (c) 2006 Richard Stoner
 * 
 * This program is in no way affiliated with Google, Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.WindowsMobile.PocketOutlook;

namespace calsyncum
{
    class OutlookInterface
    {
        OutlookSession oSession;
        public List<CalendarEvent> events;
        GoAmi mainForm;
        public DateTime startMin;
        public int countAdd;
        public int countUpdate;
        public int countDel;


        public OutlookInterface(GoAmi mainForm)
        {
            this.mainForm = mainForm;
            oSession = new OutlookSession();
            events = new List<CalendarEvent>();
            startMin = new DateTime(1970, 1, 1); // standard minimum date (also on google)            
        }

        public void copyToOutlookEvent(CalendarEvent calendarevent, Appointment aptholder)
        {
            aptholder.Body = calendarevent.description;
            //string offsetA = TimeZone.CurrentTimeZone.GetUtcOffset(calendarevent.endTime).ToString();
            //string offsetB = TimeZone.CurrentTimeZone.GetUtcOffset(calendarevent.endTime.ToLocalTime()).ToString();
            //string offsetC = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).ToString();
            aptholder.Start = calendarevent.startTime.Add(TimeZone.CurrentTimeZone.GetUtcOffset(calendarevent.startTime.ToLocalTime()));
            aptholder.AllDayEvent = calendarevent.alldayevent;
            if (calendarevent.endTime != DateTime.MinValue)
            {
                aptholder.End = calendarevent.endTime.Add(TimeZone.CurrentTimeZone.GetUtcOffset(calendarevent.endTime.ToLocalTime()));
            }
            else
            {
                if (calendarevent.alldayevent == false)
                {
                    mainForm.debug("No allday but null as endtime");
                }
            }            
            aptholder.Subject = calendarevent.subject;
            aptholder.Location = calendarevent.location;
            aptholder.BusyStatus = calendarevent.getOutlookBusyStatus();
            if (calendarevent.getOutlookReminderSet())
            {
                aptholder.ReminderSet = true;
                aptholder.ReminderMinutesBeforeStart = calendarevent.getOutlookReminderMinutesBeforeStart();
            }
        }




        public string posttooutlook(CalendarEvent calendarevent)
        {
            mainForm.debug("Start autlook add to phone");
            mainForm.debug("Google id:" + calendarevent.googleid);
            Appointment aptholder = oSession.Appointments.Items.AddNew();
            copyToOutlookEvent(calendarevent,aptholder);
            aptholder.Update();
            countAdd += 1;
            return aptholder.ItemId.ToString();            
        }
        public void downloadEvents()
        {
            mainForm.debug("Start download events on outlook");
            
            //startMin
            events.Clear();
            for (int Ocount = 0; Ocount < oSession.Appointments.Items.Count; Ocount++)
            {
                Appointment appointment = oSession.Appointments.Items[Ocount];
                if ((startMin == null) || (startMin.CompareTo(appointment.Start) < 0))
                {
                    // Only download if later than starttime
                    CalendarEvent oEvent = new CalendarEvent();
                    oEvent.alldayevent = appointment.AllDayEvent;
                    oEvent.setOutlookBusyStatus(appointment.BusyStatus);
                    oEvent.category = appointment.Categories.ToString();
                    oEvent.description = appointment.Body.ToString();
                    oEvent.location = appointment.Location;
                    if (oEvent.location == null) oEvent.location = "";
                    if (appointment.ReminderSet)
                    {
                        oEvent.setOutlookReminderMinutesBeforeStart(appointment.ReminderMinutesBeforeStart);
                    }
                    //The UTC time is equal to the local time minus the UTC offset.
                    oEvent.startTime = appointment.Start.Subtract(TimeZone.CurrentTimeZone.GetUtcOffset(appointment.Start.ToLocalTime()));
                    oEvent.endTime = appointment.End.Subtract(TimeZone.CurrentTimeZone.GetUtcOffset(appointment.End.ToLocalTime()));
                    oEvent.subject = appointment.Subject;
                    oEvent.outlookid = appointment.ItemId.ToString();
                    oEvent.hasrecurrence = (!(appointment.RecurrencePattern.RecurrenceType == RecurrenceType.NoRecurrence));
                    events.Add(oEvent);                    
                }
            }
        }
        public bool updateonoutlook(string outlookid, CalendarEvent newEvent)
        {
            mainForm.debug("Start update event on outlook");
            mainForm.debug("Outlook id:" + outlookid);
            Appointment itemtoupdate = null;
            for (int Ocount = 0; Ocount < oSession.Appointments.Items.Count; Ocount++)
            {
                if (oSession.Appointments.Items[Ocount].ItemId.ToString().Equals(outlookid))
                    itemtoupdate = oSession.Appointments.Items[Ocount];
            }
            if (itemtoupdate != null)
            {
                copyToOutlookEvent(newEvent, itemtoupdate);
                itemtoupdate.Update();
                countUpdate += 1;
                return true;
            }
            return false;
        }

        public bool deleteOnOutlook(string outlookid)
        {
            mainForm.debug("Start delete event on outlook");
            mainForm.debug("Outlook id:" + outlookid);
            Appointment itemtodelete = null;
            for (int Ocount = 0; Ocount < oSession.Appointments.Items.Count; Ocount++)
            {
                if (oSession.Appointments.Items[Ocount].ItemId.ToString().Equals(outlookid))
                    itemtodelete = oSession.Appointments.Items[Ocount];
            }
            if (itemtodelete.RecurrencePattern.RecurrenceType != RecurrenceType.NoRecurrence)
            {
                mainForm.debug("O:No recurrence support: will not delete app.");
                return false;
            }
            
            if (itemtodelete != null)
            {
                oSession.Appointments.Items.Remove(itemtodelete);
                countDel += 1;
                return true;
            }
            return false;
        }

        public CalendarEvent getEventFromId(string outlookid)
        {
            if (events.Count > 0)
            {
                //make sure the gEventlist has been populated with feed items
                CalendarEvent dummyEvent;

                for (int i = 0; i < events.Count; i++)
                {
                    dummyEvent = events[i];

                    if (dummyEvent.outlookid == outlookid)
                    {
                        return dummyEvent;
                    }
                }

            }
            return null;
        }

        /**
         * Delete appointments that contain a specific string in their description
         */
        public void deleteOnDescription(string descriptionstring)
        {
            downloadEvents();
            for (int Ocount = 0; Ocount < events.Count; Ocount++)
            {
                CalendarEvent outlookEvent = events[Ocount];
                if (outlookEvent.description.IndexOf(descriptionstring) != -1)
                {
                    deleteOnOutlook(outlookEvent.outlookid);
                }
            }            
        }
    }
}
